import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wallpaper/api/author.dart';
import 'package:wallpaper/components/AlertDialog/loading_dialog.dart';
import 'package:wallpaper/components/placeholder/appbar_base.dart';
import 'package:wallpaper/components/button/normal_button.dart';
import 'package:wallpaper/components/input/normal_input.dart';

class WallhavenApikey extends StatefulWidget {
  const WallhavenApikey({super.key});

  @override
  State<WallhavenApikey> createState() => _WallhavenApikeyState();
}

class _WallhavenApikeyState extends State<WallhavenApikey> {
  TextEditingController controller = TextEditingController();

  void setLocalApikey(String text, {String tip = '设置成功'}) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString('wallhaven_apikey', text);
    BotToast.showText(text: tip);
  }

  @override
  void initState() {
    super.initState();
    // 获取本地存储的apikey
    SharedPreferences.getInstance().then((prefs) {
      final apikey = prefs.getString('wallhaven_apikey');
      if (apikey != null) {
        controller.text = apikey;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    final List<AboutItem> items = [
      AboutItem(
        title: 'wallhaven apiKey 说明',
        subtitle:
            '本应用接入了wallhaven的api，每天可以免费获取n张图片或有频率限制(详情见官网详细说明)，如果需要更多图片，请自行申请wallhaven的api key，并将其填入到上方文本框中并确认。',
      ),
      AboutItem(
        title: 'wallhaven 官网',
        subtitle: 'https://wallhaven.cc/ 点击前往官网',
        onTap: () {
          launchUrl(
            Uri.parse('https://wallhaven.cc/'),
          );
        },
      ),
      AboutItem(
        title: '注意事项',
        subtitle:
            'wallhaven国内被墙，需要全程挂载VPN才能正常使用。注册时多换几个IP地址可能才会成功。本人使用的是用日本ip才注册成功，其他ip都失败了，所以没有测试过注册是否成功。',
      ),
      AboutItem(
        title: '关于代理',
        subtitle:
            '本软件启动时自动判断用户是否开启代理，如果开启代理，则全局网络走代理（默认端口：7890），否则使用本地网络访问。如果需要本机切换了代理，请重新启动该软件。',
      ),
    ];
    return Scaffold(
      appBar: AppbarBase(title: 'wallhaven apiKey'),
      body: Column(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: ListView(
                children: [
                  NormalInput(
                    controller: controller,
                    radius: 5,
                    onSubmitted: (text) async {
                      setLocalApikey(text);
                    },
                  ),
                  SizedBox(height: 15),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    spacing: 10,
                    children: [
                      Expanded(
                        child: NormalButton(
                          title: '重置',
                          radius: 40,
                          bgColor: const Color.fromARGB(255, 177, 177, 177),
                          onPressed: () {
                            controller.text = '';
                            setLocalApikey(controller.text, tip: '重置成功');
                          },
                        ),
                      ),
                      Expanded(
                        child: NormalButton(
                          title: '获取',
                          radius: 40,
                          bgColor: theme.primary,
                          onPressed: () async {
                            var loadingClose = LoadingDialog.showLoading(
                              message: '正在获取apikey...',
                              context: context,
                              loadingType: 1,
                            );
                            try {
                              Response res = await getWallHavenApiKey();
                              controller.text = res.data['apikey'];
                            } catch (e) {
                              print(e);
                            } finally {
                              setLocalApikey(controller.text);
                              loadingClose();
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 20),
                  for (var item in items)
                    Column(
                      children: [
                        Material(
                            color:
                                theme.primaryContainer,
                            borderRadius: BorderRadius.circular(8),
                            clipBehavior: Clip.antiAlias,
                            child: ListTile(
                              title: Text(item.title),
                              // trailing: Text('vversion'),
                              subtitle: Text(item.subtitle),
                              onTap: () {
                                if (item.onTap != null) {
                                  item.onTap!();
                                }
                              },
                            )),
                        const SizedBox(height: 10),
                      ],
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class AboutItem {
  final String title;
  final String subtitle;
  final Function()? onTap;
  const AboutItem({
    required this.title,
    required this.subtitle,
    this.onTap,
  });
}
